<template>
  <div>
    <el-upload
      :limit="1"
      action="#"
      list-type="picture-card"
      :on-preview="handlePictureCardPreview"
      :on-remove="handleRemove"
      :file-list="fileList"
      :class="{disabled:fileComputed}"
      :http-request="myUpload"
      :before-upload="beforeUpload"
    >
      <i class="el-icon-plus" />
    </el-upload>
    <el-progress v-if="showPercent" style="width:180px" :percentage="percent" />
    <el-dialog :visible.sync="dialogVisible">
      <img width="100%" :src="dialogImageUrl" alt="">
    </el-dialog>
  </div>
</template>

<script>
import COS from 'cos-js-sdk-v5'
import { v4 as uuidv4 } from 'uuid'
import path from 'path'
const cos = new COS({
  SecretId: 'AKIDFDvQCh8vAYjho6lB0XwA7n9BVZKXb8XP',
  SecretKey: 'iodYWCBtPfaGgq2xd6JBPtZ0AoFyXKqT'
})
export default {
  data () {
    return {
      dialogImageUrl: '',
      dialogVisible: false,
      fileList: [],
      showPercent: false,
      percent: 0
    }
  },
  computed: {
    fileComputed () {
      return this.fileList.length >= 1
    }
  },
  methods: {
    handleRemove (file, fileList) {
      this.fileList = fileList
    },
    handlePictureCardPreview (file) {
      this.dialogImageUrl = file.url
      this.dialogVisible = true
    },
    myUpload ({ file }) {
      cos.putObject({
        Bucket: 'qd35-1305640130',
        Region: 'ap-beijing',
        Key: uuidv4() + path.extname(file.name),
        StorageClass: 'STANDARD', // 此类写死
        Body: file, // 将本地的文件赋值给腾讯云配置
        onProgress: (params) => {
          this.percent = params.percent * 100
        }
      }, (err, data) => {
        if (err || data.statusCode !== 200) {
          return this.$message.error('上传图片失败')
        }
        this.fileList.push({ url: 'http://' + data.Location })

        this.showPercent = false // 隐藏进度条
        this.percent = 0 // 进度归0
      })
    },
    beforeUpload (file) {
      const types = ['image/jpeg', 'image/jif', 'image/bmp', 'image/png']
      if (!types.includes(file.type)) {
        this.$message.error('图片的类型只能是，jpeg/jif/bmg/png')
        return false
      }
      const maxSize = 5 * 1024 * 1024
      if (maxSize < file.size) {
        this.$message.error('图片的大小不能超过5M')
        return false
      }
      this.showPercent = true
      return true
    }
  }
}
</script>

<style >
.disabled .el-upload--picture-card {
  display: none
}
</style>
